package com.team2.outpatient_sys.service.impl;

import com.team2.outpatient_sys.dao.AdministratorDao;
import com.team2.outpatient_sys.dao.DoctorDao;
import com.team2.outpatient_sys.dao.UserDao;
import com.team2.outpatient_sys.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class LoginDetailServiceImpl implements UserDetailsService {
    @Autowired
    private AdministratorDao administratorDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String prefix = username.substring(0, 2);
        username = username.substring(2);

        return getUserDetails(prefix, username);
    }

    /**
     * 获取不同用户的登录与授权信息的封装UserDetails实现类对象
     * @param prefix 不同用户的分类前缀
     * @param username 用户名
     * @return 封装的登录与授权信息实现类对象
     */
    private UserDetails getUserDetails(String prefix, String username) {
        UserDetails userDetails;

        if ("a:".equals(prefix)) {
            // 得到管理员用户的UserDetails
            Administrator administrator = administratorDao.queryByUsername(username);

            if (administrator == null)
                throw new RuntimeException("管理员用户名不存在");

            userDetails = new AdministratorLoginDetails(administrator);
        } else if ("d:".equals(prefix)) {
            // 得到医护人员用户的UserDetails
            Doctor doctor = doctorDao.queryByUsername(username);

            if (doctor == null)
                throw new RuntimeException("医护人员用户名不存在");

            userDetails = new DoctorLoginDetails(doctor);
        } else {
            // 得到病人用户的UserDetails
            User user = userDao.queryByUsername(username);

            if (user == null)
                throw new RuntimeException("用户名不存在");

            userDetails = new UserLoginDetails(user);
        }
        return userDetails;
    }
}
